//
//  AppDelegate.m
//  ZKCompetitionApp
//
//  Created by 凯朱 on 2019/8/20.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import "SLGuideVC.h"
#import "SLHomePageVC.h"
#import <CoreLocation/CLLocation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "SLIbeaconManager.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate,UIDocumentInteractionControllerDelegate>{
    UIBackgroundTaskIdentifier backgroundTask; //用来保存后台运行任务的标示符
    NSTimer *_timer;
    NSInteger _time;
    CLLocationManager *_locationManager;
    
}
@property (nonatomic, strong)CBCentralManager *centralManager;
@property (strong, nonatomic) UIDocumentInteractionController * documentInteractionController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //初始化window
    [self initWindow];
    
    //开启防崩溃框架
    [self openAvoidCrash];
    
    //键盘弹出监听
    [self registerIQKeyboardManager];
    
    //初始化app服务
    [self initService];
    
    //初始化用户系统
    [self initUserManager];
    
    //请求权限
    [self requestPermissions];
    [self requestNotificationPermission];
    [self openDebugModel];
//    [[SLIbeaconManager sharedManager] startBackgoundMonitoring];
    [[SLIbeaconManager sharedManager] startUserDeviceMonitoring];
    [self registerAwsIotLog];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openDebugModel) name:@"kOpenDebugModelChange" object:nil];
    return YES;
}

-(void)registerAwsIotLog{
//    [AWSDDLog sharedInstance].logLevel = AWSDDLogLevelDebug;
//    [[AWSDDLog sharedInstance] addLogger:[AWSDDTTYLogger sharedInstance]];
    
}

-(void)openDebugModel{
    NSInteger tag = 90909021212;
    if ([ZCTool isOpenDebugModel]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateChatView) name:@"updateChatView" object:nil];
        ZKBaseButton *btn = [kAppWindow viewWithTag:tag];
        if (btn){
            [kAppWindow bringSubviewToFront:btn];
            return;
        }
        btn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(kScreenWidth-100, kScreenHeight-150, 60, 30);
        btn.layer.cornerRadius = 15;
        btn.layer.masksToBounds = YES;
        btn.layer.borderWidth = 1;
        btn.layer.borderColor = KColor_B.CGColor;
        [btn setTitle:@"查看日志" forState:UIControlStateNormal];
        btn.titleLabel.font = kFont(12);
        [btn setTitleColor:KColor_B forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(openChatView) forControlEvents:UIControlEventTouchUpInside];
        [kAppWindow addSubview:btn];
        [kAppWindow bringSubviewToFront:btn];
        btn.tag = tag;
    }else{
        ZKBaseButton *btn = [kAppWindow viewWithTag:tag];
        if (btn) {
            [btn removeFromSuperview];
        }
        [UserManager sharedUserManager].chatStr = [[NSMutableString alloc] initWithString:@""];
        if ([UserManager sharedUserManager].chatView) {
            [[UserManager sharedUserManager].chatView removeFromSuperview];
            [UserManager sharedUserManager].chatView = nil;
        }
    }
}

-(void)updateChatView{
    UITextView *textView = [[UserManager sharedUserManager].chatView viewWithTag:111];
    textView.text = [UserManager sharedUserManager].chatStr;
}

-(void)openChatView{
    
    if ([UserManager sharedUserManager].chatView) {
        [UserManager sharedUserManager].chatView.hidden = NO;
        [kAppWindow bringSubviewToFront:[UserManager sharedUserManager].chatView];
        UITextView *textView = [[UserManager sharedUserManager].chatView viewWithTag:111];
        textView.editable = NO;
        if ([UserManager sharedUserManager].chatStr) {
            textView.text = [UserManager sharedUserManager].chatStr;
        }
    }else{
        UIView *chatView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        chatView.backgroundColor = [KColor_1 colorWithAlphaComponent:1];
        [kAppWindow addSubview:chatView];
        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 15, kScreenWidth, kScreenHeight-85)];
        textView.backgroundColor = [UIColor blackColor];
        textView.editable = NO;
        textView.textColor = KWhiteColor_text;
        [chatView addSubview:textView];
        if ([UserManager sharedUserManager].chatStr) {
            textView.text = [UserManager sharedUserManager].chatStr;
        }
        textView.tag = 111;
        CGFloat width = (kScreenWidth)/4;
        ZKBaseButton *clearBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
        clearBtn.frame = CGRectMake(0, kScreenHeight-85, width, 85);
        [clearBtn setTitle:@"清空" forState:UIControlStateNormal];
        clearBtn.titleLabel.font = kFont(14);
        [clearBtn setTitleColor:KWhiteColor forState:UIControlStateNormal];
        [clearBtn addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
        
      
        ZKBaseButton *closeBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
        closeBtn.frame = CGRectMake(CGRectGetMaxX(clearBtn.frame), kScreenHeight-85, width, 85);
        [closeBtn setTitle:@"收起" forState:UIControlStateNormal];
        closeBtn.titleLabel.font = kFont(14);
        [closeBtn setTitleColor:KColor_O forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
        
        ZKBaseButton *copyBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
        copyBtn.frame = CGRectMake(CGRectGetMaxX(closeBtn.frame), kScreenHeight-85, width, 85);
        [copyBtn setTitle:@"当前日志" forState:UIControlStateNormal];
        copyBtn.titleLabel.font = kFont(14);
        [copyBtn setTitleColor:KColor_B forState:UIControlStateNormal];
        [copyBtn addTarget:self action:@selector(copyAction) forControlEvents:UIControlEventTouchUpInside];
        
        ZKBaseButton *historyBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
        historyBtn.frame = CGRectMake(CGRectGetMaxX(copyBtn.frame), kScreenHeight-85, width, 85);
        [historyBtn setTitle:@"历史日志" forState:UIControlStateNormal];
        historyBtn.titleLabel.font = kFont(14);
        [historyBtn setTitleColor:KRedColor forState:UIControlStateNormal];
        [historyBtn addTarget:self action:@selector(historyAction) forControlEvents:UIControlEventTouchUpInside];

        
        [chatView addSubview:copyBtn];
        [chatView addSubview:clearBtn];
        [chatView addSubview:closeBtn];
        [chatView addSubview:historyBtn];
        [kAppWindow addSubview:chatView];
        [UserManager sharedUserManager].chatView = chatView;
        [kAppWindow bringSubviewToFront:[UserManager sharedUserManager].chatView];
    }
}



-(void)copyAction{
    UITextView *textView = [[UserManager sharedUserManager].chatView viewWithTag:111];
    NSString *date = [NSString dateStrFromDate:[NSDate date] formatStr:@"yyyyMMdd_HHmmss"];
    NSString *fullName = [NSString stringWithFormat:@"UserLog_%@.txt",date];
    [self writeToTXTFileWithString:textView.text fileName:fullName];
    NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fullName];
    [ZCTool shareWithTitle:fullName filePath:theFilePath vc:[ZCTool getCurrentUIVC]];
}

-(void)historyAction{
    NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *date = [NSString dateStrFromDate:[NSDate date] formatStr:@"yyyyMMdd"];
    NSString *fullName = [NSString stringWithFormat:@"UserLog_%@.txt",date];
    NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fullName];
    [ZCTool shareWithTitle:fullName filePath:theFilePath vc:[ZCTool getCurrentUIVC]];
}

/**
 param
 string:文件内容
 fileName:文件名
 */
-(void)writeToTXTFileWithString:(NSString *)string fileName:(NSString *)fileName {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @synchronized (self) {
            //获取沙盒路径
            NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            //获取文件路径
            NSString *fullName = [NSString stringWithFormat:@"%@", fileName];
            NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fullName];
            //创建文件管理器
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //如果文件不存在 创建文件
            if(![fileManager fileExistsAtPath:theFilePath]){
                [@"" writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
            }
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:theFilePath];
            [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
            NSData* stringData  = [[NSString stringWithFormat:@"%@\n",string] dataUsingEncoding:NSUTF8StringEncoding];
            [fileHandle writeData:stringData]; //追加写入数据
            [fileHandle closeFile];
        }
    });
}


#pragma - UIDocumentInteractionControllerDelegate
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return [ZCTool getCurrentUIVC];
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return [ZCTool getCurrentUIVC].view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    return  [ZCTool getCurrentUIVC].view.frame;
}

-(void)clearAction{
    UITextView *textView = [[UserManager sharedUserManager].chatView viewWithTag:111];
    [UserManager sharedUserManager].chatStr = [[NSMutableString alloc] initWithString:@""];
    textView.text = [UserManager sharedUserManager].chatStr;
}

-(void)closeAction{
    [UserManager sharedUserManager].chatView.hidden = YES;
}


- (void)requestNotificationPermission {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self; // 设置代理
    
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"用户允许通知");
        } else {
            NSLog(@"用户拒绝通知: %@", error.localizedDescription);
        }
    }];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    // 显示通知
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
}


-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    
    [self handleUrl:url.absoluteString];
    return YES;
}

-(void)handleUrl:(NSString *)url{
    if ([url hasPrefix:@"magiclock"]) {
        NSDictionary *params = [self parseParametersFromURL:url];
        //绑定钥匙
        if (kSTRING(params[@"keyId"]).length > 0) {
            [self bindKeyWith:params];
        }
    }
}

-(void)bindKeyWith:(NSDictionary *)data{
    if (kIsTourst) {
        //记录信息
        kShowToast(@"Please login first");
        _shareInfo = data;
        return;
    }
    NSString *time = kSTRING(data[@"time"]);
    if (time.length > 0) {
        NSInteger space = [[[NSDate date] timestamp] integerValue] - [time integerValue];
        //超过2天
        if (space >= 60*60*24*2) {
            kShowToast(@"The share link is no longer valid");
            return;
        }
    }
    //绑定设备
    [ZCTool showLoadingOnKeyWindow];
    NSString *url = [NSString stringWithFormat:@"/msl_lock_key/addTmp/%@",data[@"keyId"]];
    [ZKHttpManager postWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        self->_shareInfo = nil;
        if ([code isEqualToString:@"602"]) {
            [SLTipAlertView showWith:kLocalString(@"Error") content1:kLocalString(@"Bluetooth keys are for guests only.You already own this lock") content2:@"" doneBtn:kLocalString(@"OK") cancelBtn:@"" action:^(NSInteger index) {
                
            }];
            return;
        }
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        UIViewController *vc = [ZCTool getCurrentUIVC];
        [SLTipAlertView showWith:kLocalString(@"Tips") content1:kLocalString(@"You have accpet a bluetooth key！") content2:@"" doneBtn:kLocalString(@"OK") cancelBtn:@"" action:^(NSInteger index) {
            if (![vc isKindOfClass:[SLHomePageVC class]]) {
                [vc.navigationController popToRootViewControllerAnimated:YES];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kRefreshDeviceList" object:nil];
        }];
    }];
}

- (NSDictionary *)parseParametersFromURL:(NSString *)urlString {
    NSURL *url = [NSURL URLWithString:urlString];
    // 检查 URL 是否有效
    if (!url) {
        return nil;
    }
    // 解析 URL 组件
    NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
    NSArray<NSURLQueryItem *> *queryItems = components.queryItems;
    // 创建字典以存储参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // 遍历查询项并提取 keyId 和 name
    for (NSURLQueryItem *item in queryItems) {
        if ([item.name isEqualToString:@"keyId"]) {
            parameters[@"keyId"] = item.value ? item.value : [NSNull null];
        } else if ([item.name isEqualToString:@"name"]) {
            parameters[@"name"] = item.value ? item.value : [NSNull null];
        }
        else if ([item.name isEqualToString:@"time"]) {
           parameters[@"time"] = item.value ? item.value : [NSNull null];
       }
    }
    return [parameters copy]; // 返回不可变字典
}

-(void)requestPermissions{
    //定位权限
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locationManager requestAlwaysAuthorization];
        }
    }
    
    //通知权限
    [self registerRemoteNotification];
    
    //蓝牙权限
    if (!_centralManager) {
        _centralManager = [[CBCentralManager alloc] init];
        [_centralManager scanForPeripheralsWithServices:nil options:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self->_centralManager stopScan];
        });
    }
}

/** 注册 APNs */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}


- (void)startBackgroundTask{
    
    UIApplication *application = [UIApplication sharedApplication];
    //通知系统, 我们需要后台继续执行一些逻辑
    backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
        //超过系统规定的后台运行时间, 则暂停后台逻辑
        [application endBackgroundTask:self->backgroundTask];
        self->backgroundTask = UIBackgroundTaskInvalid;
        [self destoryTimer];
        NSLog(@"后台任务停止");
        [self startBackgroundTask];
    }];
    
    //判断如果申请失败了, 返回
    if (backgroundTask == UIBackgroundTaskInvalid) {
        NSLog(@"beginground error");
        return;
    }
    //已经成功向系统争取了一些后台运行时间, 实现一些逻辑, 如网络处理
    //some code
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (!self->_timer) {
            self->_timer = [NSTimer timerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(timerHandle)
                                                 userInfo:nil
                                                  repeats:YES];
            
            [[NSRunLoop currentRunLoop] addTimer:self->_timer forMode:NSRunLoopCommonModes];
            [[NSRunLoop currentRunLoop]run];
        }
    });
    
}


-(void)destoryTimer{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

-(void)timerHandle{
    _time ++;
    NSLog(@"后台任务 - %ld",_time);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    //    [self startBackgroundTask];
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"backToApp" object:nil userInfo:nil];
    //通知系统, 我们需要后台继续执行一些逻辑
    //    [application endBackgroundTask:self->backgroundTask];
    //    self->backgroundTask = UIBackgroundTaskInvalid;
    //    [self destoryTimer];
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"backToApp" object:nil userInfo:nil];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"应用被杀死");
    [[SLBluetoothManager sharedManager] disConnectPeripheral];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    
    //自己的实现代码
    
    
    
    return YES;
    
}

@end
